const Router = require("koa-router");
const mongoose = require("mongoose");
let router = new Router();
const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt");
const fs = require("fs");
const path = require("path");

router.get("/", async ctx => {
  ctx.body = "这是用户操作首页";
});

/**
 * 用户注册接口
 */
router.post("/register", async ctx => {
  const User = mongoose.model("User");
  let newUser = new User(ctx.request.body);
  console.log(newUser);
  let n = true;
  console.log(ctx.request.body);
  await User.findOne({ userName: newUser.userName }).then(result => {
    if (result) {
      n = false;
      ctx.body = {
        code: 500,
        message: "用户名已被注册"
      };
    }
  });
  if (n) {
    await newUser
      .save()
      .then(() => {
        console.log("用户名注册成功");
        ctx.body = {
          code: 200,
          message: "注册成功"
        };
      })
      .catch(err => {
        console.log(err);
        ctx.body = {
          code: 500,
          message: "服务器错误"
        };
      });
  }
});

// 用户登录接口
router.post("/login", async ctx => {
  let loginUser = ctx.request.body;
  console.log("用户登录");
  // console.log(loginUser);
  let userName = loginUser.userName;
  let passWord = loginUser.passWord;
  // 引入 User model
  const User = mongoose.model("User");
  // 根据用户名查找用户数据
  await User.findOne({ userName: userName })
    .exec()
    .then(async result => {
      // console.log(result);
      // 找到用户则比对密码
      if (result) {
        let newUser = new User();
        await newUser
          .comparePassword(passWord, result.passWord)
          .then(isMatch => {
            if (isMatch) {
              const token = jwt.sign(
                {
                  name: result.userName,
                  avatar: result.avatar
                },
                "my_token",
                { expiresIn: "10 days" }
              );
              ctx.body = {
                code: 200,
                token: "Bearer " + token,
                message: isMatch,
                avatar: result.avatar
              };
            } else {
              ctx.body = {
                code: 500,
                message: " 密码错误"
              };
            }
          })
          .catch(err => {
            console.log(err);
            ctx.body = {
              code: 500,
              message: "服务器错误"
            };
          });
      } else {
        ctx.body = {
          code: 200,
          message: "用户名不存在"
        };
      }
    })
    .catch(err => {
      console.log(err);
      ctx.body = {
        code: 500,
        message: "服务器出错"
      };
    });
});

// 上传头像
router.post("/uploadfile", async ctx => {
  // 上传单个文件
  const file = ctx.request.files.file; // 获取上传文件
  console.log("这是源文件名");
  console.log(file.name);
  // 创建可读流
  const reader = fs.createReadStream(file.path);
  let filePath = path.join(__dirname, "../static") + `/${file.name}`;
  // 创建可写流
  const upStream = fs.createWriteStream(filePath);
  // 可读流通过管道写入可写流
  reader.pipe(upStream);
  let username = await jwt.verify(
    ctx.request.headers.authorization.split(" ")[1],
    "my_token"
  );
  username = username.name;
  const User = mongoose.model("User");
  await User.update({ userName: username }, { avatar: file.name }, function(
    err
  ) {
    if (err) {
      ctx.body = {
        code: 500,
        message: "服务器错误"
      };
    }
  });
  ctx.body = {
    code: 200,
    message: "图片上传成功"
  };
});

// 修改密码
router.post("/updPassword", async ctx => {
  console.log("开始密码修改");
  const User = mongoose.model("User");
  let username = await jwt.verify(
    ctx.request.headers.authorization.split(" ")[1],
    "my_token"
  );
  username = username.name;
  let info = ctx.request.body;
  let userMatch = false;
  // 查找用户原密码
  await User.findOne({ userName: username })
    .exec()
    .then(async result => {
      console.log(result);
      // 找到用户则比对密码
      if (result) {
        let newUser = new User();
        await newUser
          .comparePassword(info.oriPwd, result.passWord)
          .then(isMatch => {
            // 原密码匹配成功
            if (isMatch) {
              // 修改密码
              console.log("密码匹配成功");
              console.log(isMatch);
              userMatch = true;
            } else {
              console.log("2222");
              ctx.body = {
                code: 500,
                message: "原密码错误"
              };
            }
          });
      }
    });
  if (!userMatch) {
    ctx.body = {
      code: 500,
      message: "原密码错误"
    };
    return;
  }
  await bcrypt.genSalt(10, async (err, salt) => {
    console.log("密码加密处理中");
    if (err) {
      ctx.body = {
        code: 500,
        message: "服务器错误"
      };
    }
    // 加密处理
    await bcrypt.hash(info.updPwd, salt, async (err, hash) => {
      if (err) {
        ctx.body = {
          code: 500,
          message: "服务器错误"
        };
      }
      info.updPwd = hash;
      console.log(hash);
      if (userMatch) {
        console.log("开始更改密码");
        await User.update(
          { userName: username },
          { passWord: info.updPwd },
          function(err) {
            if (err) {
              console.log("密码更改出错");
              ctx.body = {
                code: 500,
                message: "服务器错误"
              };
            } else {
              console.log("密码更改成功");
              ctx.body = {
                code: 200,
                message: "密码修改成功"
              };
            }
          }
        );
      } else {
        ctx.body = {
          code: 500,
          message: "原密码错误"
        };
      }
    });
  });

  console.log(info);
  ctx.body = {
    code: 200,
    message: "密码修改成功"
  };
});

// 点击提交订单的时候验证 token 是否还有效，增加历史订单
// router.post("/payMoney", async ctx => {
//   console.log(ctx.request.headers.authorization);
//   let cart = ctx.request.body.cart; // 提交的订单
//   let cartHistory; // 历史订单
//   let user = await jwt.verify(
//     ctx.request.headers.authorization.split(" ")[1],
//     "my_token"
//   );
//   const User = mongoose.model("User");
//   await User.findOne({ userName: user.name }).then(result => {
//     console.log("找到用户");
//     // console.log(result);
//     cartHistory = result.historyCart;
//   });
//   cart = cart.concat(cartHistory); // 合并提交订单和历史订单
//   // 增加历史订单
//   await User.update({ userName: user.name }, { comment: cart }, function(err) {
//     if (err) {
//       console.log("更新出错");
//     } else {
//       console.log("更新成功");
//     }
//   });
//   await User.findOne({ userName: user.name }).then(result => {
//     console.log("找到用户");
//     console.log(result);
//   });
//   ctx.body = {
//     code: 200,
//     message: "token 有效，可以购买"
//   };
// });

// 查找订单
// router.get("/historyCart", async ctx => {
//   let cartInfo;
//   let user = await jwt.verify(
//     ctx.request.headers.authorization.split(" ")[1],
//     "my_token"
//   );
//   const User = mongoose.model("User");
//   await User.findOne({ userName: user.name }).then(result => {
//     console.log(result);
//     cartInfo = result.historyCart;
//   });
//   ctx.body = {
//     code: 200,
//     cartInfo: cartInfo,
//     message: "查找成功"
//   };
// });

// 验证用户登录状态
router.get("/correct", async ctx => {
  ctx.body = {
    code: 200,
    message: "登录状态没有过期"
  };
});

module.exports = router;
